package com.jthinker.blog.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * User: Gang Chen
 * Date: 2015/6/28 14:51
 */
public class SpringUtils implements ApplicationContextAware
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringUtils.class);
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        LOGGER.info("inject applicationContext [{}]", applicationContext);

        if (LOGGER.isDebugEnabled())
        {
            String[] services = applicationContext.getBeanNamesForType(Object.class);
            LOGGER.debug("list all services:  {}{} ", SystemUtils.LINE_SEPARATOR, StringUtils.join(services, " # "));
        }

        if (applicationContext != null)
        {
            context = applicationContext;
        }
    }

    public static <T> T getBean(String name)
    {
        Object o = context.getBean(name);
        return o != null ? (T) o : null;
    }

    public static <T> T getBean(Class<T> clazz)
    {
        return context.getBean(clazz);
    }

    public static ApplicationContext getContext()
    {
        return context;
    }
}
